package com.hg.library.manager;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.net.wifi.WifiInfo;
import android.net.wifi.WifiManager;
import android.os.storage.StorageManager;

/**
 * Created by admin on 2017/1/10.
 */

public class NetworkManager {

    private Context mContext;
    private WifiBroadcast wifiBroadcast;

    public NetworkManager(Context mContext) {
        this.mContext = mContext;
    }

    public static NetworkManager from(Context context){
        return new NetworkManager(context);
    }

    public NetworkManager registerListener(OnNetworkChangedListener l){
        IntentFilter intentFilter = new IntentFilter();
        intentFilter.addAction(WifiManager.WIFI_STATE_CHANGED_ACTION);
        intentFilter.addAction(WifiManager.RSSI_CHANGED_ACTION);

        if (wifiBroadcast != null){
            wifiBroadcast.onDestroy();
            mContext.unregisterReceiver(wifiBroadcast);
        }

        mContext.registerReceiver(wifiBroadcast = new WifiBroadcast(l), intentFilter);

        return this;
    }

    public void unregisterListener(){
        if (wifiBroadcast != null){
            mContext.unregisterReceiver(wifiBroadcast);
        }
    }

    private static class WifiBroadcast extends BroadcastReceiver {

        private OnNetworkChangedListener l;

        public WifiBroadcast(OnNetworkChangedListener l) {
            this.l = l;
        }

        @Override
        public void onReceive(Context context, Intent intent) {
            if (intent.getAction().equals(WifiManager.RSSI_CHANGED_ACTION)){

                WifiManager wifiManager = (WifiManager) context.getSystemService(context.WIFI_SERVICE);
                WifiInfo wifiInfo = wifiManager.getConnectionInfo();

                if (wifiInfo.getBSSID() != null) {

                    int signalLevel = WifiManager.calculateSignalLevel(wifiInfo.getRssi(), 10);

                    if (l != null){
                        NetworkState networkState = new NetworkState();
                        networkState.SIGNAL_LEVEL = signalLevel;
                        l.onNetworkChanged(networkState);
                    }
                }
            }
        }

        public void onDestroy(){
            l = null;
        }
    }

    public interface OnNetworkChangedListener{
        void onNetworkChanged(NetworkState networkState);
    }

    public static class NetworkState{

        public int SIGNAL_LEVEL;
    }
}
